import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dialog/custom_dialog.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';


/// 自定义toast（消息提示）
/// 注意：toast显示后，需要手动移除，否则会一直显示
/// 注意要dispose，资源竞争的问题，loadingBoxShow方法也进行了释放操作，理论上没问题
class ToastUtil {
  /// 加载框对象
  static OverlayEntry? _loadingEntry;

  /// 显示消息
  static void show({
    required BuildContext context,
    required String msg,
    int seconds = 2,
  }) {
    // 创建一个OverlayEntry对象
    OverlayEntry overlayEntry = OverlayEntry(builder: (context) {
      return Positioned(
        top: ScreenUtil().screenHeight * 0.2,
        child: Container(
          width: ScreenUtil().screenWidth,
          alignment: Alignment.center,
          child: Center(
            child: Card(
              color: const Color.fromRGBO(0, 0, 0, 0.4),
              child: Padding(
                padding: EdgeInsets.all(24),
                child: Text(
                  msg,
                  style: FontUtil.fontWhile1(24),
                ),
              ),
            ),
          ),
        ),
      );
    });

    //往Overlay中插入插入OverlayEntry
    Overlay.of(context).insert(overlayEntry);
    //两秒后,移除Toast
    // Future.delayed(Duration(seconds: seconds)).then((value) {
    //   overlayEntry.remove();
    // });
    Timer(Duration(seconds: seconds), () {
      overlayEntry.remove();
    });
  }

  /// 自定义加载框
  // static void showLoadingDialog(BuildContext context) {
  //   showDialog(
  //     context: context,
  //     barrierDismissible: false, // 点击遮罩不关闭对话框
  //     builder: (context) {
  //       return const CustomDialog();
  //     },
  //   );
  // }

  /// 自定义加载框显示方法
  static void loadingBoxShow(BuildContext context) {
    // 清除上一次的loading对象
    if (_loadingEntry != null) {
      _loadingEntry?.remove();
      _loadingEntry = null;
    }
    // 创建加载框对象
    _loadingEntry =   OverlayEntry(
      builder: (context) {
        return const CustomDialog();
      },
    );
    //往Overlay中插入插入OverlayEntry
    Overlay.of(context).insert(_loadingEntry!);
  }

  /// 自定义加载框删除演示方法方法<br>
  /// 最好在页面dispose放一个，防止页面生命周期结束后还有加载框未消除
  static void loadingBoxRemove() {
    if (_loadingEntry != null) {
      _loadingEntry!.remove();
      _loadingEntry = null;
    }
  }

  // context：页面控制器
  // contentWidget：提示内容组件，与contentText必须有一个有值
  // contentText：提示内容，与contentWidget必须有一个有值
  // contentTextColor：提示内容字体颜色
  // contentStyle：提示内容字体样式
  // btnLeftShow: 左边按钮是否显示
  // btnLeftText：左边按钮提示，返回false，遮罩返回null，默认值为"取消"
  // btnLeftTextColor：左边按钮提示字体颜色
  // btnLeftStyle：左边按钮字体样式
  // btnLeftBackgroundColor：左边按钮背景色
  // btnRightText：右边按钮提示，返回true，遮罩返回null，默认值为"确认"
  // btnRightTextColor：右边按钮提示字体颜色
  // btnRightStyle：右边按钮字体样式
  // btnRightBackgroundColor：右边按钮背景色
  // barrierDismissible: 点击对话框barrier(遮罩)时是否关闭它
  /// 自定义弹出框
  static Future<bool?> showDialogBox({
    required BuildContext context,
    Widget? titleWidget,
    String? titleText,
    TextAlign titleTextAlign = TextAlign.center,
    Color? titleTextColor,
    TextStyle? titleStyle,
    Widget? contentWidget,
    String contentText = "",
    TextAlign contentTextAlign = TextAlign.center,
    Color? contentTextColor,
    TextStyle? contentStyle,
    bool btnLeftShow = true,
    String btnLeftText = "取消",
    Color? btnLeftTextColor,
    TextStyle? btnLeftStyle,
    Color? btnLeftBackgroundColor,
    String btnRightText = "确定",
    Color? btnRightTextColor,
    TextStyle? btnRightStyle,
    Color? btnRightBackgroundColor,
    bool barrierDismissible = true,
  }) async {
    // 标题字体
    TextStyle? titleTextStyle;
    if (titleWidget == null) {
      titleTextStyle = titleStyle ??
          TextStyle(
            color: titleTextColor ?? colorBlack1,
            fontWeight: FontWeight.w500,
            fontSize: 22,
          );
    }
    // 标题组件
    Widget? titleShowWidget;
    if (titleWidget != null) {
      titleShowWidget = titleWidget;
    } else {
      titleShowWidget = titleText == null
          ? null
          : Text(
              titleText,
              textAlign: titleTextAlign,
            );
    }
    // 内容字体
    TextStyle? contentTextStyle;
    if (contentWidget == null) {
      contentTextStyle = contentStyle ??
          TextStyle(
            color: contentTextColor ?? colorBlack1,
            fontWeight: FontWeight.w400,
            fontSize: 28,
          );
    }

    // 对话框显示
    return showDialog(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (context) {
        return AlertDialog(
          surfaceTintColor: colorWhite1,
          titlePadding: titleShowWidget == null
              ? null
              : EdgeInsets.only(left: 30, right: 30, top: 30),
          title: titleShowWidget,
          titleTextStyle: titleTextStyle,
          contentPadding: EdgeInsets.only(left: 30, right: 30, top: 30),
          content: contentWidget ??
              Text(
                contentText,
                textAlign: contentTextAlign,
              ),
          contentTextStyle: contentTextStyle,
          // 圆角
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          actionsPadding: EdgeInsets.only(
            left: 30,
            right: 30,
            bottom: 30,
            top: 40,
          ),
          actionsAlignment: MainAxisAlignment.end,
          actions: [
            if (btnLeftShow)
              _btnItem(
                context: context,
                btnType: false,
                btnText: btnLeftText,
                btnTextColor: btnLeftTextColor,
                btnTextStyle: btnLeftStyle,
                btnBackgroundColor: btnLeftBackgroundColor,
              ),
            _btnItem(
              context: context,
              btnType: true,
              btnText: btnRightText,
              btnTextColor: btnRightTextColor,
              btnTextStyle: btnRightStyle,
              btnBackgroundColor: btnRightBackgroundColor,
            ),
          ],
        );
      },
    );
  }

  /// 对话框按钮
  static Widget _btnItem({
    required BuildContext context,
    required bool btnType,
    required String btnText,
    Color? btnTextColor,
    TextStyle? btnTextStyle,
    Color? btnBackgroundColor,
  }) {
    // 背景颜色
    btnBackgroundColor ??= btnType ? colorBlue1 : null;
    // 字体颜色
    btnTextColor ??= btnType ? colorWhite1 : colorBlue1;

    // 内容显示
    return GestureDetector(
      onTap: () {
        // 按钮只有返回？
        Navigator.pop(context,btnType);
      },
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 16),
        decoration: BoxDecoration(
          color: btnBackgroundColor,
          borderRadius: BorderRadius.circular(30),
        ),
        child: Text(
          btnText,
          textAlign: TextAlign.center,
          style: btnTextStyle ??
              TextStyle(
                color: btnTextColor,
                fontWeight: FontWeight.w400,
                fontSize: 14,
              ),
        ),
      ),
    );
  }
}
